package com.starchen.optimalselection.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.admin.mapper.AdminMenuMapper;
import com.starchen.optimalselection.admin.mapper.AdminRoleMenuMapper;
import com.starchen.optimalselection.admin.model.AdminMenu;
import com.starchen.optimalselection.admin.model.AdminRoleMenu;
import com.starchen.optimalselection.admin.model.form.AssginMenuForm;
import com.starchen.optimalselection.admin.service.AdminRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daxilong
 * @date 2025/4/12 10:17
 */
@Service
public class AdminRoleMenuServiceImpl extends ServiceImpl<AdminRoleMenuMapper, AdminRoleMenu> implements AdminRoleMenuService {

    @Autowired
    private AdminMenuMapper adminMenuMapper;

    //根据角色分配菜单
    @Override
    public List<AdminMenu> findMenuByRoleId(Long roleId) {
        //获取所有菜单 status=1
        QueryWrapper<AdminMenu> wrapperMenu = new QueryWrapper<>();
        wrapperMenu.eq("status",1);
        List<AdminMenu> menuList = adminMenuMapper.selectList(wrapperMenu);

        //根据角色id查询 角色分配过的菜单列表
        QueryWrapper<AdminRoleMenu> wrapperRoleMenu = new QueryWrapper<>();
        wrapperRoleMenu.eq("role_id",roleId);
        List<AdminRoleMenu> relations = baseMapper.selectList(wrapperRoleMenu);

        //从第二步查询列表中，获取角色分配所有菜单id
        List<Long> menuIds = relations.stream().map( item -> item.getMenuId()).collect(Collectors.toList());

        //数据处理：isSelect 如果菜单选中 true，否则false
        // 拿着分配菜单id 和 所有菜单比对，有相同的，让isSelect值true
        menuList.stream().forEach(item -> {
            if(menuIds.contains(item.getId())){
                item.setSelect(true);
            }
            else {
                item.setSelect(false);
            }
        });
        return menuList;
    }

    /**
     * 给角色分配菜单权限
     */
    @Override
    public void doAssign(AssginMenuForm assginMenuVo) {
        //根据角色id删除菜单权限
        QueryWrapper<AdminRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",assginMenuVo.getRoleId());
        baseMapper.delete(wrapper);

        //遍历菜单id列表，一个一个进行添加
        List<Long> menuIdList = assginMenuVo.getMenuIdList();
        List<AdminRoleMenu> adminRoleMenuList = new ArrayList<>();
        for (Long menuId:menuIdList) {
            AdminRoleMenu sysRoleMenu = new AdminRoleMenu();
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenu.setRoleId(assginMenuVo.getRoleId());
            adminRoleMenuList.add(sysRoleMenu);
        }

        saveBatch(adminRoleMenuList);
    }

}
